package cn.shiro.shiroservice.common.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransaction;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * &#064;Time 2024 一月 星期三 23:00
 *
 * @author ShangGuan
 */
public class MybatisUtils {
    private static Configuration configuration;
    private static Connection connection;
    private static JdbcTransaction jdbcTransaction;

    private static SqlSessionFactory factory;


    public static SqlSession getSqlSession() {
        return factory.openSession();
    }

    public static Configuration getConfiguration() {
        return configuration;
    }

    public static Connection getConnection() {
        return connection;
    }

    public static JdbcTransaction getJdbcTransaction() {
        return jdbcTransaction;
    }

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybaits-config.xml");
            SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
            factory = factoryBuilder.build(inputStream);
            configuration = factory.getConfiguration();
            jdbcTransaction = new JdbcTransaction(factory.openSession().getConnection());
            try {
                connection = jdbcTransaction.getConnection();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            jdbcTransaction = new JdbcTransaction(connection);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
